layui.use(['table', 'laydate', 'admin', 'ax', 'func', 'form', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var form = layui.form;
    var layer = layui.layer;

    /**
     * 管理
     */
    var BtyGoodsPay = {
        tableId: "btyGoodsPayTable"
    };


    //年月选择器
    laydate.render({
        elem: '#month'
        , type: 'month'
    });

    form.on('submit(btnSubmit)', function (data) {
        BtyGoodsPayinitDatas();
    });

    BtyGoodsPayinitDatas = function () {
        if ($('#month').val() == "") {
            Feng.error("请选择月份");
            return;
        }
        var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/initData", function (data) {
            if (data.code == 1) {
                Feng.error("初始化数据失败!" + data.message);
                return;
            }
            Feng.success("初始化数据成功！");
            table.reload(BtyGoodsPay.tableId);

        }, function (data) {
            Feng.error("添加失败！" + data.responseJSON.message)
        });
        ajax.set("month", $("#month").val());
        ajax.start();
        return false;
    };

    /**
     * 同步店名
     */
    form.on('submit(btnSyn)', function (data) {
        BtyGoodsbtnSyn();
    });

    BtyGoodsbtnSyn = function () {

        if ($('#month').val() == "") {
            Feng.error("请选择月份");
            return;
        }
        loadIndex = layer.load('正在同步...',2, { shade: [0.15, '#ccc'] });
     setTimeout(()=>{
         var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/synData", function (data) {
             if (data.code == 1) {
                 Feng.error("初始化数据失败!" + data.message);
                 layer.close(loadIndex);
                 return;
             }
             Feng.success("初始化数据成功！");
             layer.close(loadIndex);
             table.reload(BtyGoodsPay.tableId);

         }, function (data) {
             Feng.error("添加失败！" + data.responseJSON.message);
             layer.close(loadIndex);
         });
         ajax.set("month", $("#month").val());
         ajax.start();
         return false;
     },100)
    };

    //监听单元格编辑
    table.on('edit(btyGoodsPayTable)', function (obj) {
        var value = obj.value, //得到修改后的值
            data = obj.data, //得到所在行所有键值
            field = obj.field; //得到字段

        var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
        var oldtext = $(selector).text();

        if (data.status == 3) {
            layer.msg('已经通过货赔审核，不能再修改数据！', {icon: 4},);
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //酱料酒水鱼平板货赔金额字段校验
        if (field == "mainPay" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //餐具货赔金额字段校验
        if (field == "canJu" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //罚款金额字段校验
        if (field == "faKuan" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //漏扣金额字段校验
        if (field == "missed" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        if (field == "sumMoney" && isNaN(value)) {
            Feng.error("修改失败，货赔总金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        if (field == "cwDeduction") {
            if (Math.floor(value) != value){
                Feng.error("修改失败，财务扣款必须填写整数");
                $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
                return false;
            }
        }


        //金额1
        if (field == "money1" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //金额2
        if (field == "money2" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //金额2
        if (field == "money3" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //金额2
        if (field == "money4" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        //金额2
        if (field == "money5" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }
        //金额2
        if (field == "dzMoney" && isNaN(value)) {
            Feng.error("金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }


        $.ajax({
            type: "GET",
            url: "/btyGoodsPay/editItem",
            datatype: "json",
            data: data,
            success: function (data) {
                // let _new = (Number($(obj.tr.selector + ' td[data-field="mainPay"] div').text()) * 1000) + (Number($(obj.tr.selector + ' td[data-field="canJu"] div').text()) * 1000)
                //     + (Number($(obj.tr.selector + ' td[data-field="faKuan"] div').text()) * 1000) + (Number($(obj.tr.selector + ' td[data-field="missed"] div').text()) * 1000);
                //
                // $(obj.tr.selector + ' td[data-field="sumMoney"] div').text(_new / 1000);

                //layui.shuxinMd();
                //table.reload(BtyGoodsPay.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
            }
        });
    });

    BtyGoodsPay.onSendItem = function (data) {

        var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/send", function (data) {
            if (data.success == true) {
                Feng.success("发送成功!");
                table.reload(BtyGoodsPay.tableId);
            } else {
                Feng.error(data.message);
            }


        }, function (data) {
            Feng.error("发送失败!" + data.responseJSON.message + "!");
        });
        ajax.set("id", data.id);
        ajax.start();

    };

    /**
     * 点击审核按钮
     * @param data
     */
    BtyGoodsPay.onAuditItem = function (data) {
        let index = layer.open({
            area: ['300px', '200px'],
            title: '审核',
            btn: ['通过', '驳回'],
            btnAlign: 'c',
            type: 1,
            async: false,
            content: '<div style="padding: 20px 20px;">是否确认通过审核？</div>',
            yes: function (index, layero) {
                //提交审核结果 通过状态为3：已通过
                BtyGoodsPay.shenHe(3, data.id);
                table.reload(BtyGoodsPay.tableId);
                layer.close(index);
            },
            btn2: function (index, layero,) {

                //提交审核结果 驳回状态为4：已驳回
                BtyGoodsPay.shenHe(4, data.id);
                layer.close(index);
            },
        });

    };

    /**
     * 设置人员
     * @param data
     */
    BtyGoodsPay.setUp = function (data) {
        if (data.status == 3) {
            layer.msg('已经通过货赔审核，不能再设置人员！', {icon: 4},);
            return false;
        }
        var url = Feng.ctxPath + '/btyGoodsPay/selectDz?id=' + data.id + "&yaoma=" + data.yaoma + "&dzBh=" + data.dzBh + "&bh1=" + data.bh1 + "&bh2=" + data.bh2 + "&bh3=" + data.bh3 + "&bh4=" + data.bh4 + "&bh5=" + data.bh5;

        layer.open({
            type: 2,
            title: '选择店长门店：' + data.dm,
            area: ['550px', '510px'],
            content: url,
            end: function () {
                //获取详情信息，填充表单
                var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/detail?id=" + data.id);
                var result = ajax.start();
                table.reload(BtyGoodsPay.tableId);
            },
            cancel: function (index) {
            }
        });
    };

    /**
     * 提交审核结果
     */
    BtyGoodsPay.shenHe = function (status, id,) {
        let obj = {};
        obj.id = id;
        obj.status = status;
        //obj.content = reason;

        $.ajax({
            type: "post",
            url: "/btyGoodsPay/audit",
            data: obj,
            async: false,
            success: function (rs) {
                if (rs.success) {
                    if (status == 3) {
                        layer.msg('已通过！');
                    } else {
                        layer.msg('已驳回！');
                    }
                } else {
                    Feng.error(rs.message);
                }
                // parent.location.reload();
                table.reload(BtyGoodsPay.tableId);
            }
        });
    };

    /**
     * 撤回
     * @param data
     */
    BtyGoodsPay.onRevokeItem = function (data) {
        let index = layer.open({
            area: ['300px', '200px'],
            title: '撤回',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            type: 1,
            async: false,
            content: '<div style="padding: 20px 20px;">注意：每月1号-11号可撤回已通过审核数据!</br>确认要撤回？</div>',
            yes: function (index, layero) {
                //提交审核结果 通过状态为3：已通过
                BtyGoodsPay.chehui(0, data.id);
                table.reload(BtyGoodsPay.tableId);
                layer.close(index);
            },
            btn2: function (index, layero,) {
                layer.close(index);
            },
        });

    };
    /**
     * 提交撤回请求
     */
    BtyGoodsPay.chehui = function (status, id,) {
        let obj = {};
        obj.id = id;
        obj.status = status;
        //obj.content = reason;
        $.ajax({
            type: "post",
            url: "/btyGoodsPay/revoke",
            data: obj,
            async: false,
            success: function (rs) {
                if (rs.success) {
                    layer.msg('已撤回！');
                } else {
                    Feng.error(rs.message);
                }
                // parent.location.reload();
                table.reload(BtyGoodsPay.tableId);
            }
        });
    };

    // 批量发送店长
    $('#batchSend').click(function () {
        BtyGoodsPay.batchSend();
    });
    // 按月导出
    $('#batchExport').click(function () {
        var month = $('#month').val();
        if (month == "" || month == undefined || month == null) {
            Feng.error("请选择月份");
        } else {
            //获取导出Excel的数据
            var url = Feng.ctxPath + "/btyGoodsPay/listExport?month=" + month;
            location.href = url;
        }
    });

    //同步货赔
    $('#btnSum').click(function () {
        BtyGoodsPay.btnSum();
    });

    //批量审核
    $('#btnAudit').click(function () {
        BtyGoodsPay.btnAudit();
    });

    BtyGoodsPay.shenHeBatch = function (status, ids) {
        let obj = {};
        obj.ids = ids;
        obj.status = status;

        $.ajax({
            type: "post",
            url: "/btyGoodsPay/auditBatch",
            data: obj,
            async: false,
            success: function (rs) {

                if (rs.code == 201) {
                    Feng.success(rs.message);
                } else {
                    if (rs.success) {

                        if (status == 3) {
                            layer.msg('已通过！');
                        } else {
                            layer.msg('已驳回！');
                        }
                    } else {
                        Feng.error(rs.message);
                    }
                }

                table.reload(BtyGoodsPay.tableId);
            }
        });
    };

    //点击批量审核
    BtyGoodsPay.btnAudit = function () {

        var checkRows = table.checkStatus(BtyGoodsPay.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量审核的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }

            let index = layer.open({
                area: ['300px', '200px'],
                title: '审核',
                btn: ['通过', '驳回'],
                btnAlign: 'c',
                type: 1,
                async: false,
                content: '<div style="padding: 20px 20px;">是否确认通过审核？</div>',
                yes: function (index, layero) {
                    //提交审核结果 通过状态为3：已通过
                    BtyGoodsPay.shenHeBatch(3, ids);
                    table.reload(BtyGoodsPay.tableId);
                    layer.close(index);
                },
                btn2: function (index, layero) {

                    //提交审核结果 驳回状态为4：已驳回
                    BtyGoodsPay.shenHeBatch(4, ids);
                    layer.close(index);
                 },
            });

            // ajax.set("ids", ids);
            // ajax.start();

        }
    };

    /**
     * 点击同步货赔
     */
    var loadIndex;
    BtyGoodsPay.btnSum = function (data) {
        loadIndex = layer.load('正在导入...',2, { shade: [0.15, '#ccc'] });
        $.ajax({
            type: "PUT",
            url: "/btyGoodsPay/editSumMoney",
            datatype: "json",
            data: {"date":$('#month').val()},
            success: function (data) {
                table.reload(BtyGoodsPay.tableId);
                Feng.success("同步完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };

    BtyGoodsPay.batchSend = function () {
        var checkRows = table.checkStatus(BtyGoodsPay.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量发送的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/batchSend", function (data) {
                    if (data.code = 201) {
                        Feng.success(data.message);
                    } else {
                        Feng.success("发送成功!");
                        table.reload(BtyGoodsPay.tableId);
                    }


                }, function (data) {
                    Feng.error("发送失败!" + data.responseJSON.message + "!");
                });
                ajax.set("ids", ids);
                ajax.start();
            };
            Feng.confirm("是否批量发送?", operation);
        }
    };
    /**
     * 初始化表格的列
     */
    BtyGoodsPay.initColumn = function () {
        return [[
            {type: 'checkbox', fixed: 'left'},
            // {field: 'id', hide: true, title: ''},
            {field: 'dm', sort: false, title: '店名', fixed: 'left', width: 180},
            {field: 'yaoma', sort: true, title: '妖码',width: 100,align: 'center'},
            //{field: 'cwry', sort: true, title: '财务人员'},
            {field: 'cwm', sort: false, title: '编码', width: 60, align: 'center'},
            {field: 'shopownerView', title: '店长', width: 60, align: 'center'},
            {field: 'mobile', title: '店长手机', align: 'center'},
            // {field: 'mainPay', sort: false, title: '酱料酒水鱼平板货赔', edit: 'text',  totalRow: true,align: 'center',width: 70,},
            // {field: 'canJu', sort: false, title: '餐具货赔', edit: 'text', width: 70, totalRow: true,align: 'center'},
            // {field: 'faKuan', sort: false, title: '罚款', edit: 'text', totalRow: true,width: 50,align: 'center'},
            // {field: 'missed', sort: false, title: '漏扣', edit: 'text', totalRow: true,width: 50,align: 'center'},
            {field: 'sumMoney', sort: false, title: '货赔总金额', edit: 'text', totalRow: true, width: 100, align: 'center'},
            {field: 'cwDeduction', sort: false, title: '财务扣款', totalRow: true, width: 100, align: 'center'},
            {field: 'month', sort: false, title: '月份', width: 60, align: 'center'},

            {field: 'dzName', title: '店长', edit: 'text', event: 'setdz', width: 100, align: 'center'},
            {field: 'dzMoney', sort: false, title: '店长金额', edit: 'text', width: 100, align: 'center'},
            {field: 'name1', sort: false, title: '人员1',width: 100,align: 'center'},
            {field: 'money1', sort: false, title: '人员1金额', width: 100,align: 'center'},
            {field: 'name2', sort: false, title: '人员2',width: 100,align: 'center'},
            {field: 'money2', sort: false, title: '人员2金额', width: 100,align: 'center'},
            {field: 'name3', sort: false, title: '人员3',width: 100,align: 'center'},
            {field: 'money3', sort: false, title: '人员3金额', width: 100,align: 'center'},
            {field: 'name4', sort: false, title: '人员4',width: 100,align: 'center'},
            {field: 'money4', sort: false, title: '人员4金额', width: 100,align: 'center'},
            {field: 'name5', sort: false, title: '人员5',width: 100,align: 'center'},
            {field: 'money5', sort: false, title: '人员5金额',width: 100,align: 'center'},
            {
                field: 'status',
                sort: false,
                title: '状态',
                templet: '#statusTpl',
                fixed: 'right',
                align: 'center',
                width: 60,
            },
            {align: 'left', toolbar: '#tableBar', title: '操作', minWidth: '250', fixed: 'right', align: 'center'},
            {field: 'remark', sort: false, title: '备注', edit: 'text', fixed: 'right', align: 'center'}
            // {field: 'createTime', sort: true, title: '创建时间'},
            // {field: 'createUser', sort: true, title: '创建人'},
            // {field: 'updateTime', sort: true, title: '更新时间'},
            // {field: 'updateUser', sort: true, title: '更新人'},

        ]];
    };


    /**
     * 点击查询按钮
     */
    var queryData = {};
    BtyGoodsPay.search = function () {
        queryData['dm'] = $('#dm').val();
        queryData['month'] = $('#month').val();
        queryData['status'] = $('#status').val();

        table.reload(BtyGoodsPay.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加对话框
     */
    BtyGoodsPay.openAddDlg = function () {
        func.open({
            title: '添加',
            content: Feng.ctxPath + '/btyGoodsPay/add',
            tableId: BtyGoodsPay.tableId
        });
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    BtyGoodsPay.openEditDlg = function (data) {
        func.open({
            title: '修改',
            content: Feng.ctxPath + '/btyGoodsPay/edit?id=' + data.id,
            tableId: BtyGoodsPay.tableId
        });
    };


    /**
     * 导出excel按钮
     */
    BtyGoodsPay.exportExcel = function () {
        var checkRows = table.checkStatus(BtyGoodsPay.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BtyGoodsPay.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(BtyGoodsPay.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    BtyGoodsPay.tableCfg = table.render({
        elem: '#' + BtyGoodsPay.tableId,
        url: Feng.ctxPath + '/btyGoodsPay/list',
        page: true,
        height: "full-59",
        totalRow: true,	//开启合计行
        cellMinWidth: 100,
        where: {month: $("#month").val()},
        cols: BtyGoodsPay.initColumn()
    });


    //首次加载表格
    queryData['month'] = $('#month').val();
    BtyGoodsPay.tableCfg.where = queryData;
    table.render(BtyGoodsPay.tableCfg);

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BtyGoodsPay.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

        BtyGoodsPay.openAddDlg();

    });

    // 导出excel
    $('#btnExp').click(function () {
        BtyGoodsPay.exportExcel();
    });

    /**
     * 选择店长
     * @param data
     */
    BtyGoodsPay.selDz = function (obj, data) {
        var url = Feng.ctxPath + '/btyGoodsPay/selectDz?id=' + data.id + "&yaoma=" + data.yaoma + "&dzBh=" + data.dzBh + "&bh1=" + data.bh1 + "&bh2=" + data.bh2 + "&bh3=" + data.bh3 + "&bh4=" + data.bh4 + "&bh5=" + data.bh5;

        layer.open({
            type: 2,
            title: '选择店长门店：' + data.dm,
            area: ['550px', '510px'],
            content: url,
            end: function () {
                //获取详情信息，填充表单
                var ajax = new $ax(Feng.ctxPath + "/btyGoodsPay/detail?id=" + data.id);
                var result = ajax.start();
                obj.update({
                    dzName: result.data.dzName
                });
                table.reload(BtyGoodsPay.tableId);
            },
            cancel: function (index) {


            }
        });
    };

    // 工具条点击事件
    table.on('tool(' + BtyGoodsPay.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            BtyGoodsPay.openEditDlg(data);
        } else if (layEvent === 'delete') {
            BtyGoodsPay.onDeleteItem(data);
        } else if (layEvent === 'send') {
            BtyGoodsPay.onSendItem(data);
        } else if (layEvent === 'audit') {
            BtyGoodsPay.onAuditItem(data);
        } else if (layEvent === 'revoke') {
            BtyGoodsPay.onRevokeItem(data);
        } else if (layEvent === 'setdz') {
            if (data.status == 3) {
                layer.msg('已经通过货赔审核，不能再修改店长！', {icon: 4},);
                return false;
            }

            BtyGoodsPay.selDz(obj, data);
        }else if (layEvent === 'setUp'){
            BtyGoodsPay.setUp(data);
        }


        // obj.update({
        //     sign: value
        // });


    });


});








